package wsi.gui.resolve.model;

import java.io.File;

import wsi.exp.Exp2TreeToEntity;
import wsi.exp.ExpFolderController;
import wsi.exp.exp5.JudgeFile;
import wsi.exp.exp5.JudgeFileManager;
import wsi.function.Function;
import wsi.function.FunctionController;

public class JudgeItemIterator {

	public JudgeItemIterator() {

	}

	public JudgeItem next() {
		FunctionController fctrl = FunctionController.shared();

		File dir = ExpFolderController.shared().getFolderForExp5();
		Function function;

		for (File ws : dir.listFiles()) {
			if (!ws.isDirectory())
				continue;

			for (File fdir : ws.listFiles()) {
				if (!ws.isDirectory())
					continue;

				function = fctrl.getFunction(ws.getName(), fdir.getName());

				if (function == null)
					continue;

				if (!Exp2TreeToEntity.isFunctionCorrectlyDetected(function))
					continue;

				JudgeItem item = next(function, fdir);

				if (item != null)
					return item;
			}
		}

		System.out.println("[info] completed.");
		return null;
	}

	private JudgeItem next(Function function, File functionDir) {
		// System.out.printf("[info] get next for %s\n",
		// function.getFullName());

		JudgeFileManager fm = new JudgeFileManager(function);

		JudgeItem item;

		for (File x : fm.getXmlFiles()) {
			File jfile = fm.getJudgeFile(x.getName());

			if (jfile != null) {
				JudgeFile judgeFile = new JudgeFile(jfile);

				if (judgeFile.isEmpty() || judgeFile.isAllJudged())
					continue;
			}

			item = new JudgeItem(function, x, jfile);

			if (!item.isValid())
				continue;

			return item;
		}

		return null;
	}
}
